import React, { useState, useRef } from 'react';
import { Form, Input, Button, Card, Divider, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import Captcha from '../../components/Captcha';
import './index.css';

interface LoginForm {
  username: string;
  password: string;
}

interface TenantInfo {
  id: string;
  name: string;
}

interface LoginState {
  tenantList: TenantInfo[];
  selectedTenant: TenantInfo | null;
  showTenantSelection: boolean;
  userCredentials: LoginForm | null;
  loading: boolean;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const videoRef = useRef<HTMLVideoElement>(null);

  const [loginState, setLoginState] = useState<LoginState>({
    tenantList: [],
    selectedTenant: null,
    showTenantSelection: false,
    userCredentials: null,
    loading: false
  });
  const [showCaptcha, setShowCaptcha] = useState(false);
  const [loginAttempts, setLoginAttempts] = useState(0);
  const [pendingLoginData, setPendingLoginData] = useState<any>(null);

  // 登录配置
  const loginConfig = {
    systemName: '云魔方智能平台'
  };

  // 模拟租户数据
  const mockTenants: TenantInfo[] = [
    { id: '1', name: '默认租户' },
    { id: '2', name: '测试租户' }
  ];

  // 处理表单提交
  const handleSubmit = async (values: LoginForm) => {
    try {
      setLoginState(prev => ({ ...prev, loading: true }));
      
      // 模拟获取租户列表
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (values.username === 'admin' && values.password === 'admin123') {
        // 检查是否需要验证码（登录失败次数超过2次）
        if (loginAttempts >= 2) {
          setPendingLoginData(values);
          setShowCaptcha(true);
          setLoginState(prev => ({ ...prev, loading: false }));
          return;
        }
        
        // 继续正常登录流程
        proceedWithLogin(values);
      } else {
        setLoginAttempts(prev => prev + 1);
        message.error('用户名或密码错误');
        setLoginState(prev => ({ ...prev, loading: false }));
      }
    } catch (error) {
      message.error('登录失败');
      setLoginState(prev => ({ ...prev, loading: false }));
    }
  };

  // 继续登录流程
  const proceedWithLogin = async (values: LoginForm) => {
    // 模拟多租户场景
    if (mockTenants.length === 1) {
      // 单租户直接登录
      handleDirectLogin(values, mockTenants[0]);
    } else if (mockTenants.length > 1) {
      // 多租户显示选择界面
      setLoginState(prev => ({
        ...prev,
        tenantList: mockTenants,
        showTenantSelection: true,
        userCredentials: values,
        loading: false
      }));
    } else {
      message.error('未找到可用租户');
      setLoginState(prev => ({ ...prev, loading: false }));
    }
  };

  // 直接登录
  const handleDirectLogin = (credentials: LoginForm, tenant: TenantInfo) => {
    // 模拟登录成功
    localStorage.setItem('ACCESS_TOKEN', 'mock-token');
    localStorage.setItem('TENANT_ID', tenant.id);
    message.success('登录成功');
    navigate('/');
  };

  // 处理租户选择
  const handleTenantSelect = (tenant: TenantInfo) => {
    if (loginState.userCredentials) {
      setLoginState(prev => ({ ...prev, selectedTenant: tenant }));
      handleDirectLogin(loginState.userCredentials, tenant);
    }
  };

  // 验证码验证成功
  const handleCaptchaSuccess = (captchaCode: string) => {
    if (pendingLoginData) {
      // 重置登录失败次数
      setLoginAttempts(0);
      // 继续登录流程
      proceedWithLogin(pendingLoginData);
      setPendingLoginData(null);
    }
  };

  // 关闭验证码弹窗
  const handleCaptchaClose = () => {
    setShowCaptcha(false);
    setPendingLoginData(null);
    setLoginState(prev => ({ ...prev, loading: false }));
  };

  // 返回登录页面
  const handleBackToLogin = () => {
    setLoginState({
      tenantList: [],
      selectedTenant: null,
      showTenantSelection: false,
      userCredentials: null,
      loading: false
    });
    form.resetFields();
  };

  return (
    <div className="login-container">
      {/* 背景视频 */}
      <video
        ref={videoRef}
        className="background-video"
        autoPlay
        muted
        loop
        playsInline
        preload="none"
        poster="/assets/bg-login.webp"
      >
        <source src="/assets/bg-login.mp4" type="video/mp4" />
        您的浏览器不支持视频播放
      </video>

      {/* 登录表单区域 */}
      <div className="welcome">
        {loginState.showTenantSelection ? (
          // 租户选择界面
          <div className="container">
            <div className="greet mb-20">
              <h2 style={{ fontSize: '30px', margin: 0 }}>选择企业点击登录</h2>
              <p className="secondary-text">检测到您的账号关联了多个企业，请选择要登录的企业</p>
            </div>

            <Card className="tenant-card">
              <div className="tenant-list">
                {loginState.tenantList.map((tenant) => (
                  <div key={tenant.id} className="list-item">
                    <Button
                      type="primary"
                      size="large"
                      block
                      onClick={() => handleTenantSelect(tenant)}
                      className="tenant-button"
                    >
                      {tenant.name}
                    </Button>
                  </div>
                ))}
              </div>
              <Button
                size="large"
                block
                onClick={handleBackToLogin}
                className="back-button"
              >
                返回上一页
              </Button>
            </Card>
          </div>
        ) : (
          // 登录表单界面
          <div className="container">
            <img src="/assets/logo.png" alt="logo" className="logo" />
            <div className="greet mb-10">
              <Divider style={{ borderColor: 'rgba(0, 0, 0, 0.88)' }}>
                <h4 className="mb-0">{loginConfig.systemName}</h4>
              </Divider>
            </div>

            <Form
              form={form}
              name="login"
              className="login-form"
              size="large"
              onFinish={handleSubmit}
              autoComplete="off"
            >
              <Form.Item
                name="username"
                rules={[{ required: true, message: '请输入账户名称' }]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="请输入账户名称"
                  size="large"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入账户密码' }]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请输入账户密码"
                  size="large"
                />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  size="large"
                  block
                  loading={loginState.loading}
                  className="login-button"
                >
                  登录
                </Button>
              </Form.Item>
            </Form>

            <div className="login-tips">
              <p>测试账号：admin / admin123</p>
            </div>
          </div>
        )}
      </div>

      {/* 验证码弹窗 */}
      <Captcha
        visible={showCaptcha}
        onClose={handleCaptchaClose}
        onSuccess={handleCaptchaSuccess}
      />
    </div>
  );
};

export default Login;